package com.ahtg.minispring.core;

import com.ahtg.minispring.utils.StringUtil;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 类扫描器
 */
public class ClassScanner {

    private static String CLASS_FILE_SUFFIX = ".class";

    private  static List<Class<?>> classList = new ArrayList<>();


    public static List<Class<?>> scanClasses(String packageName) throws IOException, ClassNotFoundException {
        //容器，存储扫描到的类


        String filePackPath = packageName.replace('.', '/');
        Enumeration<URL> dir = Thread.currentThread().getContextClassLoader().getResources(filePackPath);
        String packPrefix = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        if(System.getProperty("file.separator").equals("\\")){
            packPrefix = packPrefix.substring(1);
        }
        // 遍历资源文件
        while(dir.hasMoreElements()){
            URL url = dir.nextElement();
            String protocol = url.getProtocol();

            if("file".equals(protocol)){
                File file = new File(url.getPath());
                scanFile(file,packPrefix);
            } else if("jar".equals(protocol)){
                System.out.println(protocol);
            }
        }
        return classList;
    }

    private static void scanFile(File file,String packPrefix) throws ClassNotFoundException {
        File[] fs = file.listFiles();
        for(int i = 0; fs != null && i < fs.length; i++){
            File f = fs[i];
            String path = f.getAbsolutePath();
            if(f.isDirectory()){
                scanFile(f,packPrefix);
            }else{
                if(path.endsWith(CLASS_FILE_SUFFIX)){
                    String className = StringUtil.getPackageByPath(f, packPrefix); // 获取包名
                    classList.add(Class.forName(className));
                }
            }

        }
    }

}
